provider "alicloud" {
  # If not set, cn-beijing will be used.
  region = "cn-guangzhou"
}

resource "alicloud_vpc" "default" {
  cidr_block = "172.16.0.0/16"
}

variable "name" {
  default = "terraform-hello"
}

data "alicloud_zones" "default" {
  available_disk_category = "cloud_efficiency"
  available_resource_creation = "VSwitch"
}

data "alicloud_images" "default" {
  name_regex = "^ubuntu_[0-9]+_[0-9]+_x64*"
  owners     = "system"
}


resource "alicloud_vpc" "terraform_vpc" {
  vpc_name = var.name
  cidr_block = "172.16.0.0/16"
}

resource "alicloud_vswitch" "vswitch" {
  vpc_id = alicloud_vpc.terraform_vpc.id
  cidr_block = "172.16.0.0/24"
  zone_id = data.alicloud_zones.default.zones.0.id
  vswitch_name = var.name
}

resource "alicloud_security_group" "terraform_security_group" {
  name = "terraform_security_group"
  vpc_id = alicloud_vpc.terraform_vpc.id
}


resource "alicloud_security_group_rule" "allow_tcp_in" {
    for_each = toset([ "22/22", "443/443", "80/80" ])
        type = "ingress"
        nic_type = "intranet"
        policy = "accept"
        ip_protocol = "tcp"
        port_range = each.value
        priority = 1
        security_group_id = alicloud_security_group.terraform_security_group.id
        cidr_ip = "0.0.0.0/0"
}

resource "alicloud_kms_key" "terraform_key" {
  description = "terraform key"
  pending_window_in_days = "7"
  status = "Enabled"
}

resource "alicloud_instance" "terraform_ecs" {
  availability_zone = data.alicloud_zones.default.zones.0.id
  security_groups = alicloud_security_group.terraform_security_group.*.id
  instance_type = "ecs.e-c1m2.large"
  system_disk_category = "cloud_essd"
  image_id                   = data.alicloud_images.default.ids[0]
  instance_name              = var.name
  vswitch_id                 = alicloud_vswitch.vswitch.id
  internet_max_bandwidth_out = 5
  system_disk_size = 40
  instance_charge_type = "PostPaid"
  internet_charge_type = "PayByTraffic"



}
